/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.basics.service;

import com.alibaba.fastjson.JSON;
import com.rzico.base.BaseMapper;
import com.rzico.base.CommResult;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.*;
import com.rzico.basics.model.*;
import com.rzico.core.entity.SysMch;
import com.rzico.exception.CustomException;
import com.rzico.util.CodeGenerator;
import lombok.var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rzico.basics.mapper.ProductMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <pre>
 * 产品档案业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class ProductService extends BaseServiceImpl<Product, String> {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ProductTagService productTagService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Override
    public BaseMapper<Product, String> getMapper() {
        return productMapper;
    }

    private void InitProduct(Product product) {
        if (product.getMaxLimit()==null) {
            product.setMaxLimit(0);
        }
        if (product.getMinLimit()==null) {
            product.setMinLimit(1);
        }
        if (product.getUnitRate()==null) {
            product.setUnitRate(BigDecimal.ONE);
        }
        if (product.getStock()==null) {
            product.setStock(0);
        }
        if (product.getSubType()==null) {
            product.setSubType(0);
        }
        if (product.getShippingMethod()==null) {
            product.setShippingMethod("0");
        }
        if (product.getAllocatedStock()==null) {
            product.setAllocatedStock(0);
        }
        if (product.getWeight()==null) {
            product.setWeight(BigDecimal.ZERO);
        }
        if (product.getCost()==null) {
            product.setCost(BigDecimal.ZERO);
        }
        if (product.getDeleted()==null) {
            product.setDeleted(false);
        }
        if (product.getUnitRate()==null) {
            product.setUnitRate(BigDecimal.ONE);
        }
        if (product.getUnitType()==null) {
            product.setUnitType(0);
        }
        if (product.getPoint()==null) {
            product.setPoint(0);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public List<Product> insertProduct(List<Product> products,Long [] tagIds) {
        //1、保存主表
        Goods goods = new Goods();
        goods.setCreateDate(new Date());
        goods.setReview(0L);
        goods.setTotalSale(0L);
        goods.setHits(0L);
        int affectCount = goodsService.insertUseGeneratedKeys(goods);
        if (affectCount <= 0){
            throw new CustomException("保存商品主表失败");
        }

        //2、保存子表
        int listCount = 0;

        ProductArticle article = null;
        for (Product product : products){
            InitProduct(product);

            product.setCreateDate(new Date());
            product.setGoodsId(goods.getId());
            product.setDeleted(false);
            product.setIsMetaVideo(false);
            if (product.getIsList()){
                listCount++;
            }


            if (product.getArticle()!=null) {
                article = product.getArticle();
            }

            if (article!=null) {
                if (article.getProductMeta()!=null && article.getProductMeta().getVideo()!=null) {
                    product.setIsMetaVideo(true);
                }
                product.setContent(article.getContent());
                product.setMeta(JSON.toJSONString(article.getProductMeta()));
            }

            super.insertUseGeneratedKeys(product);

        }

        if (listCount > 1){
            throw new CustomException("显示商品数超过1个,请检查");
        }

        Long mainProductId = null;

        for (Product product : products){
            if (product.getIsList()){
                mainProductId = product.getId();
                break;
            }
        }

        for (Product product : products) {
            if (!product.getUnitType().equals(0)) {
                product.setMainProductId(mainProductId);
            } else {
                product.setMainProductId(product.getId());
            }
            super.updateByPrimaryKeySelective(product);
        }

        if (tagIds!=null) {
            for (Long tagId : tagIds) {
                ProductTag adTag = new ProductTag();
                adTag.setProducts(products.get(0).getId());
                adTag.setTags(tagId);
                productTagService.insert(adTag);
            }
        }

        Product params = new Product();
        params.setGoodsId(goods.getId());
        params.setDeleted(false);
        return productMapper.select(params);
    }

    /**
     * 批量添加/删除标签
     * @param products
     * @param tagIds
     * @param type 1.上架；0.下架
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateProductsTag(List<Product> products,Long [] tagIds, String type) {
        for (Long tagId : tagIds) {
            for (Product product : products) {
                ProductTag tag = new ProductTag();
                tag.setProducts(product.getId());
                tag.setTags(tagId);
                productTagService.delete(tag);
            }
        }
        if ("1".equals(type)) {
            for (Long tagId : tagIds) {
                for (Product product : products) {
                    ProductTag tag = new ProductTag();
                    tag.setProducts(product.getId());
                    tag.setTags(tagId);
                    productTagService.insert(tag);
                }
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public int updateProduct(List<Product> products,Long [] tagIds) {

        int rw = 0;
        ProductArticle article = null;
        Enterprise enterprise = enterpriseService.getCurrent();
        if (products.size()==0) {
            throw new CustomException("商品无效数据");
        }

        Long mainProductId = null;
        Product mainProduct =null;

        for (Product product : products){
            if (product.getIsList()){
                mainProductId = product.getId();
                mainProduct = productMapper.selectByPrimaryKey(mainProductId);
                break;
            }
        }

        if (mainProduct==null) {
            throw new CustomException("不能删除主规格");
        }

        if (mainProduct.getGoodsId()==null) {
            throw new CustomException("不能删除主规格");
        }

        Integer publishType = mainProduct.getPublishType();

        Product params = new Product();
        params.setGoodsId(mainProduct.getGoodsId());
        List<Product> oldProducts = productMapper.select(params);
        for (Product product : products) {
            if (product.getId()!=null) {
                for (Product pdt : oldProducts) {
                    if (product.getId().equals(pdt.getId())) {
                        oldProducts.remove(pdt);
                        break;
                    }
                }
            }
        }

        for (Product product : products){
            Product pdt = productMapper.selectByPrimaryKey(product.getId());
            if (null == pdt){
                for (Product opt : oldProducts) {
                    //符合条件，恢复删除的记录
                    if (product.getSn().equals(opt.getSn()) && product.getSpec().equals(opt.getSpec()) && product.getUnit().equals(opt.getUnit())) {
                        product.setId(opt.getId());
                        oldProducts.remove(opt);
                        break;
                    }
                }
                InitProduct(product);
                product.setPublishType(publishType);
                product.setMainProductId(mainProductId);
                product.setCreateDate(new Date());
                product.setDeleted(false);
                product.setIsMetaVideo(false);
                product.setGoodsId(mainProduct.getGoodsId());
                product.setEnterpriseId(enterprise.getId());

                if (product.getArticle()!=null) {
                    article = product.getArticle();
                }

                if (article!=null) {
                    if (article.getProductMeta()!=null && article.getProductMeta().getVideo()!=null) {
                        product.setIsMetaVideo(true);
                    }
                    product.setContent(article.getContent());
                    product.setMeta(JSON.toJSONString(article.getProductMeta()));
                }

                if (publishType==1) {
                    product.setCost(pdt.getCost());
                    product.setSn(null);
                }

                if (product.getId()==null) {
                    if (publishType==1) {
                        throw new CustomException("芸市场商品不能新增");
                    }
                    rw += super.insertUseGeneratedKeys(product);
                } else {
                    rw += super.updateByPrimaryKeySelective(product);
                }


            } else if (null != pdt){

                if (pdt.getDeleted()){
                    product.setDeleted(false);
                }

                if (product.getArticle()!=null) {
                    article = product.getArticle();
                }

                if (article!=null) {
                    product.setContent(article.getContent());
                    product.setMeta(JSON.toJSONString(article.getProductMeta()));
                }

                if (publishType==1) {
                    product.setCost(pdt.getCost());
                    product.setSn(null);
                }

                rw += super.updateByPrimaryKeySelective(product);
            }

            pdt = productMapper.selectByPrimaryKey(product.getId());
            if (!pdt.getUnitType().equals(0)){
                pdt.setMainProductId(mainProductId);
            }else{
                pdt.setMainProductId(product.getId());
            }
            pdt.setFreightId(product.getFreightId());
            pdt.setDistributionId(product.getDistributionId());
            pdt.setBrandId(product.getBrandId());
            productMapper.updateByPrimaryKey(pdt);

        }

        //删除无效商品
        for (Product dpt:oldProducts) {
            dpt.setDeleted(true);
            super.updateByPrimaryKeySelective(dpt);
        }

        ProductTag adTag = new ProductTag();
        adTag.setProducts(products.get(0).getId());
        productTagService.delete(adTag);

        if (tagIds!=null) {
            if (tagIds != null) {
                for (Long tagId : tagIds) {
                    adTag = new ProductTag();
                    adTag.setProducts(products.get(0).getId());
                    adTag.setTags(tagId);
                    productTagService.insert(adTag);
                }
            }
        }

        return rw;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(Object[] ids) {
        int rw = 0;
        for (Object id:ids) {
            Product product = selectByPrimaryKey(id);
            product.setDeleted(true);
            rw = rw + super.updateByPrimaryKeySelective(product);
        }
        return rw;
    }


    public List<Product> findBySn(Enterprise enterprise,String sn) {
        Map<String,Object> params = new HashMap<>();
        params.put("enterpriseId",enterprise.getId());
        params.put("sn",sn);
        return productMapper.selectList(params);
    }

    public List<Product> copyProduct(Enterprise enterprise,Product product) {

        Map<String,Object> params = new HashMap<>();
        params.put("enterpriseId",product.getEnterpriseId());
        params.put("goodsId",product.getGoodsId());
        params.put("deleted",false);
        params.put("sortField","is_list");
        params.put("sortType","desc");

        List<Product> productList = productMapper.selectList(params);

        Goods goods = new Goods();
        goods.setCreateDate(new Date());
        goods.setReview(0L);
        goods.setTotalSale(0L);
        goods.setHits(0L);

        int affectCount = goodsService.insertUseGeneratedKeys(goods);

        Long mainProductId = null;

        List<Product> data = new ArrayList<>();
        for (Product d:productList) {
            Product prod = new Product();
            BeanUtils.copyProperties(d,prod);
            prod.setDeleted(false);
            prod.setGoodsId(goods.getId());
            prod.setName(prod.getName());
            prod.setEnterpriseId(enterprise.getId());
            prod.setFreightId(null);
            prod.setProductCategoryId(null);
            prod.setStock(0);
            prod.setIsMarketable(false);
            prod.setDistributionId(null);
            prod.setSupplierId(null);
            prod.setBrandId(null);
            super.insertUseGeneratedKeys(prod);
            if (prod.getIsList()) {
                mainProductId = prod.getId();
            }
            data.add(prod);
        }

        for (Product prod:data) {
            if (!prod.getUnitType().equals(0)) {
                prod.setMainProductId(mainProductId);
            } else {
                prod.setMainProductId(prod.getId());
            }
            super.updateByPrimaryKeySelective(prod);
        }

        return data;
    }


    public List<ProductVo> selectProductVoList(Map<String, Object> params) {
        return productMapper.selectProductVoList(params);
    }

    public List<PromotionVo> getPromotionVo(Long goodsId) {
        Map<String,Object> params = new HashMap<>();
        params.put("goodsId",goodsId);
        return productMapper.getPromotionVo(params);
    }

    @Transactional(rollbackFor = Exception.class)
    public int updateMarketable(Long goodsId,Boolean value) {

        Product product = new Product();
        product.setGoodsId(goodsId);
        List<Product> products = select(product);

        for (Product prod:products) {
            prod.setIsMarketable(value);
            prod.setModifyDate(new Date());
            productMapper.updateByPrimaryKey(prod);
        }
        return products.size();

    }

    @Transactional(rollbackFor = Exception.class)
    public int batchUpdate(List<Product> products) {
        for (Product prod:products) {
            Product product = new Product();
            product.setGoodsId(prod.getGoodsId());
            List<Product> productList = select(product);
            for (Product pd : productList) {
                pd.setProductCategoryId(prod.getProductCategoryId());
                pd.setIsMarketable(prod.getIsMarketable());
                pd.setModifyDate(new Date());
                productMapper.updateByPrimaryKeySelective(pd);
            }
        }
        return products.size();
    }



    public int decStock(Long id,BigDecimal value) {
        Map<String,Object> params = new HashMap<>();
        params.put("id",id);
        params.put("value",value);
        return productMapper.decStock(params);
    }

    public int addStock(Long id,BigDecimal value) {
        Map<String,Object> params = new HashMap<>();
        params.put("id",id);
        params.put("value",value);
        return productMapper.addStock(params);
    }

    public List<ProductUploadVo> upload(List<ProductUploadVo> list,String ModifyBy,Long enterpriseId){
        boolean isExecult=true;
        for (ProductUploadVo product : list) {
            product.setResult("");
            //检查
            if (product.getMarketPrice()==null){
                product.setResult("市场价不能为空,");
                isExecult=false;
            }
            if (product.getName()==null){
                String result = product.getResult();
                product.setResult(result+"商品名称不能为空,");
                isExecult=false;
            }
            if (product.getVip1price()==null){
                String result = product.getResult();
                product.setResult(result+"vip1价格不能为空,");
                isExecult=false;
            }
            if (product.getVip2price()==null){
                String result = product.getResult();
                product.setResult(result+"vip2价格不能为空,");
                isExecult=false;
            }
            if (product.getSpec1()==null){
                String result = product.getResult();
                product.setResult(result+"规格1不能为空,");
                isExecult=false;
            }if (product.getSn()==null){
                String result = product.getResult();
                product.setResult(result+"货号不能为空,");
                isExecult=false;
            }
            if (product.getPrice()==null){
                String result = product.getResult();
                product.setResult(result+"销售价不能为空");
                isExecult=false;
            }
            if(isExecult){
                //执行sql
                if (product.getId()==null){
                    Product pd=new Product();

                    pd.setMarketPrice(product.getMarketPrice());
                    pd.setName(product.getName());
                    pd.setSpec1(product.getSpec1());
                    pd.setSpec2(product.getSpec2());
                    pd.setPrice(product.getPrice());
                    pd.setVip1price(product.getVip1price());
                    pd.setVip2price(product.getVip2price());
                    pd.setVip3price(product.getVip3price());
                    pd.setVip4price(product.getVip4price());
                    pd.setVip5price(product.getVip5price());
                    pd.setFreightId(product.getFreightId());
                    pd.setBrandId(product.getBrandId());
                    pd.setProductCategoryId(product.getProductCategoryId());
                    pd.setProductCategoryName(product.getProductCategoryName());
                    pd.setStock(product.getStock());
                    pd.setSubTitle(product.getSubTitle());
                    pd.setMinLimit(product.getMinLimit());
                    pd.setMaxLimit(product.getMaxLimit());
                    pd.setSubType(product.getSubType());
                    pd.setPoint(product.getPoint());
                    pd.setSn(product.getSn());
                    pd.setUnit(product.getUnit());
                    pd.setIsMarketable(false);
                    pd.setModifyBy(ModifyBy);
                    pd.setEnterpriseId(enterpriseId);
                    pd.setCreateDate(new Date());
                    if (product.getCost()==null)
                        pd.setCost(new BigDecimal("0.0"));
                    else
                        pd.setCost(product.getCost());
                    pd.setDeleted(false);
                    pd.setIsList(true);
                    pd.setIsMetaVideo(false);
                    pd.setUnitRate(new BigDecimal("1"));
                    pd.setUnitType(0);
                    pd.setWeight(new BigDecimal("0"));
                    pd.setThumbnail(null);
                    pd.setAllocatedStock(0);
                    pd.setType(0);
                    pd.setPublishType(0);
                    pd.setSubType(0);
                    pd.setQuality(0);

                    Goods goods = new Goods();
                    goods.setCreateDate(new Date());
                    goods.setReview(0L);
                    goods.setTotalSale(0L);
                    goods.setHits(0L);
                    int affectCount = goodsService.insertUseGeneratedKeys(goods);
                    if (affectCount <= 0){
                        throw new CustomException("保存商品主表失败");
                    }
                    pd.setGoodsId(goods.getId());

                    super.insertUseGeneratedKeys(pd);

                    pd.setMainProductId(pd.getId());
                    super.updateByPrimaryKeySelective(pd);

                    product.setResult("success");
                }
                else {
                    //更新操作
                    Product upModel=selectByPrimaryKey(product.getId());
                    upModel.setMarketPrice(product.getMarketPrice());
                    upModel.setName(product.getName());
                    upModel.setSpec1(product.getSpec1());
                    upModel.setSpec2(product.getSpec2());
                    upModel.setPrice(product.getPrice());
                    upModel.setVip1price(product.getVip1price());
                    upModel.setVip2price(product.getVip2price());
                    upModel.setVip3price(product.getVip3price());
                    upModel.setVip4price(product.getVip4price());
                    upModel.setVip5price(product.getVip5price());
                    if(product.getCost()==null)
                        upModel.setCost(new BigDecimal("0.0"));
                    else
                        upModel.setCost(product.getCost());
                    upModel.setSn(product.getSn());
                    upModel.setUnit(product.getUnit());
                    upModel.setModifyDate(new Date());
                    upModel.setMinLimit(product.getMinLimit());
                    upModel.setMaxLimit(product.getMaxLimit());
                    super.updateByPrimaryKeySelective(upModel);
                    product.setResult("success");
                }
            }
            else{
                product.setResult("未导入 "+product.getResult());
            }
        }
        return  list;
    }
}
